using System.Collections;
using System.Collections.Generic;
using System.IO;
using cfg;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using Luban;
using SimpleJSON;

public class LotteryNumber : MonoBehaviour
{
    public Text displayNumTxt;
    public Text conditionTxt;

    public Button startBtn;
    public Button getBtn;
    public Button startChoiceBtn;
    public Dropdown dropdown;
    // Start is called before the first frame update
    void Start()
    {
        getBtn.onClick.AddListener(() =>
        {
            StartGetData();
        });
        
        startBtn.onClick.AddListener((() => { StartLottery();}));

        startChoiceBtn.onClick.AddListener((() => { StartChoiceLottery(); }));
    }

    private NumberManager _manager;
    void StartGetData()
    {
        StartCoroutine(WaitAll());
        _manager = new NumberManager();
    }

    private Tables tables;
    IEnumerator WaitAll()
    {
        yield return StartCoroutine(GetData("demo_tbitem.json.txt"));
        yield return StartCoroutine(GetData("game_tbdata.json.txt"));

        tables = new cfg.Tables(LoadJson);
        // table
        Debug.Log(tables.Tbgamedata.DataList[tables.Tbgamedata.DataList.Count-1]);

        displayNumTxt.text = _manager.Output();
        RefreshDrop();
        // dropdown.AddOptions();
        // Debug.Log(tables.Tbdata.DataList[tables.Tbdata.DataList.Count-1]);
    }

    void RefreshDrop()
    {
        dropdown.ClearOptions();
        List<string> lists = new List<string>();
        int id = -1;
        for (int i = 0; i < tables.Tbgamedata.DataList.Count; i++)
        {
            id = tables.Tbgamedata.DataList[i].Id;
            lists.Add(id.ToString());
        }
        
        dropdown.AddOptions(lists);
        dropdown.value = lists.Count - 1;
    }

    void StartLottery()
    {
        int id = int.Parse(dropdown.options[dropdown.value].text);
        _manager.StartLottery(tables.Tbgamedata.Get(id));
        displayNumTxt.text = _manager.Output();

        GUIUtility.systemCopyBuffer = displayNumTxt.text.ToString();
    }

    void StartChoiceLottery()
    {
        int id = int.Parse(dropdown.options[dropdown.value].text);
        _manager.StartChoiceLottery(tables.Tbgamedata.Get(id));
        displayNumTxt.text = _manager.Output();

        GUIUtility.systemCopyBuffer = displayNumTxt.text.ToString();
    }

    private static JSONNode LoadJson(string file)
    {
        string path = Path.Combine(Application.persistentDataPath, file + ".json.txt");
        if (File.Exists(path))
        {
            return JSON.Parse(File.ReadAllText(path, System.Text.Encoding.UTF8));
        }
        path  = Path.Combine(Application.streamingAssetsPath, file +  ".json.txt");
        return JSON.Parse(File.ReadAllText(path, System.Text.Encoding.UTF8));
    }

    
    UnityWebRequest webRequest;
    public string downUrl;
    public bool isSim = false;
    IEnumerator GetData(string fileName)
    {
        string url = downUrl;
#if UNITY_EDITOR
        if (!isSim)
        {
            url = Application.streamingAssetsPath;
            yield break;
        }
#endif

        webRequest = UnityWebRequest.Get(Path.Combine(url,fileName));
        Debug.Log(webRequest.url);
        webRequest.timeout = 30;
        yield return webRequest.SendWebRequest();

        if (webRequest.isNetworkError)
        {
            Debug.Log("Download Error:" + webRequest.error);
        }
        else
        {

            var File = webRequest.downloadHandler.data;
            FileStream nFile = new FileStream(Path.Combine(Application.persistentDataPath, fileName), FileMode.Create);
            nFile.Write(File, 0, File.Length);

            nFile.Close();
        }

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
